const PENDING = "pending"; //等待
const FULFILLED = "fulfilled"; //成功
const REJECTED = "rejected"; //失败

// 创建MyPromise 类
class MyPromise {
  constructor(executor) {
    try {
      executor(this.resolve, this.reject);
    } catch (error) {
      this.reject(error);
    }
  }
  // promise 状态
  status = PENDING;
  // 成功之后的值
  value = undefined;
  // 失败之后的原因
  reason = undefined;
  // 成功回调
  successCallback = [];
  // 失败回调
  failCallback = [];

  resolve = (value) => {
    // 判断是不是等待状态 阻止程序向下执行 promise状态改变后不重复调用
    if (this.status !== PENDING) return;
    //状态改为成功
    this.status = FULFILLED;
    //保存成功之后的值
    this.value = value;
    // (处理异步情况) 判断成功回调是否存在 如果存在 调用  多个回调
    while (this.successCallback.length) this.successCallback.shift()();
  };
  reject = (reason) => {
    // 判断是不是等待状态 阻止程序向下执行 promise状态改变后不重复调用
    if (this.status !== PENDING) return;
    //状态改为失败
    this.status = REJECTED;
    //保存失败之后的原因
    this.reason = reason;
    // (处理异步情况) 判断失败回调是否存在 如果存在 调用  多个回调
    while (this.failCallback.length) this.failCallback.shift()();
  };
  then(successCallback, failCallback) {
    // 实现 then 方法中参数 可传 可不传
    successCallback = successCallback ? successCallback : (value) => value;
    failCallback = failCallback
      ? failCallback
      : (reason) => {
          throw reason;
        };
    // 返回一个promise对象 并返回 实现then方法的链式调用
    let promise2 = new MyPromise((resolve, reject) => {
      //判断状态
      if (this.status === FULFILLED) {
        setTimeout(() => {
          try {
            let x = successCallback(this.value);
            resolvePromise(promise2, x, resolve, reject);
          } catch (error) {
            reject(error);
          }
        }, 0);
      } else if (this.status === REJECTED) {
        setTimeout(() => {
          try {
            let x = failCallback(this.reason);
            resolvePromise(promise2, x, resolve, reject);
          } catch (error) {
            reject(error);
          }
        }, 0);
      } else {
        //等待
        //将成功回调和失败回调存储起来
        this.successCallback.push(() => {
          setTimeout(() => {
            try {
              let x = successCallback(this.value);
              resolvePromise(promise2, x, resolve, reject);
            } catch (error) {
              reject(error);
            }
          }, 0);
        });
        this.failCallback.push(() => {
          setTimeout(() => {
            try {
              let x = failCallback(this.reason);
              resolvePromise(promise2, x, resolve, reject);
            } catch (error) {
              reject(error);
            }
          }, 0);
        });
      }
    });
    return promise2;
  }
  finally(callback) {
    //返回 promise 对象
    return this.then(
      (value) => {
        return MyPromise.resolve(callback().then(() => value));
      },
      () => {
        return MyPromise.resolve(
          callback().then(() => {
            throw reason;
          })
        );
      }
    );
  }
  catch(failCallback) {
    return new MyPromise(undefined, failCallback);
  }
  static all(array) {
    let result = [];
    let index = 0;
    return new MyPromise((resolve,reject)=>{
      function addData(key, value) {
        result[key] = value;
        index++;
        if (index == array.length) {
          resolve(result);
        }
      }
      for (let i = 0; i < array.length; i++) {
        let current = array[i];
        //判断current 是不是 promise 对象
        if (current instanceof MyPromise) {
          //promise 对象
          current.then(
            (value) => addData(i, value),
            (reason) => reject(reason)
          );
        } else {
          //普通值
          addData(i, array[i]);
        }
      }
    })
    
  }
  static resolve(value) {
    if (value instanceof MyPromise) return value;
    return new MyPromise((resolve) => resolve(value));
  }
}

function resolvePromise(promise2, x, resolve, reject) {
  // 判断 then方法循环调用Promsse自身
  if (promise2 === x) {
    return reject(
      new TypeError("Chaining cycle detected for promise #<Promise>")
    );
  }
  if (x instanceof MyPromise) {
    // promise 对象
    x.then(resolve, reject);
  } else {
    // 普通值
    resolve(x);
  }
}

//导出 MyPromise
module.exports = MyPromise;
